package com.whz.governance.redislimiter.config;

import com.google.common.collect.Lists;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * @author whz
 */
@Data
@ConfigurationProperties(prefix = "tongyu.redis.rate-limiter")
public class RedisRateLimiterProperties {

    /**
     * enable rate limit filter
     */
    private boolean enable = false;
    /**
     * a map of the path pattern and its rate limit config
     */
    private Map<String, RateLimiterConfig> config;

    /**
     * white ip list, not limit
     */
    private List<String> whiteIp = Lists.newLinkedList();


    @Data
    public static class RateLimiterConfig {
        /**
         * token or leaky
         */
        private BucketType algorithm = BucketType.TOKEN;
        /**
         * token rate
         */
        private int replenishRate = 5;

        /**
         * 令牌流速的时间单位,默认秒
         */
        private ChronoUnit chronoUnit = ChronoUnit.SECONDS;
        /**
         * bucket capacity,must greater than replenishRate
         */
        private int burstCapacity = replenishRate << 1;
        /**
         * tokens of per request
         */
        private int requestedTokens = 1;

        /**
         * enable inner ip access,not limit
         */
        private boolean intranetEnable = true;
    }

    public static enum BucketType {
        /**
         * Flow shaping to eliminate peaks
         */
        TOKEN,
        /**
         * Flow shaping, limiting the average speed
         */
        LEAKY;
    }
}